package file_watcher

import (
	"bytes"
	"github.com/julienschmidt/httprouter"
	"log"
	"net/http"
)

func parseDta(r *http.Request)(string){
	var err error
	var buf bytes.Buffer
	_, err = buf.ReadFrom(r.Body)
	if err != nil{
		log.Fatal(err)
	}
	return buf.String()
}

func HttpAddFile(watcher *FileWatcher)(httprouter.Handle){

	handler := func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
		defer func() {
			err := r.Body.Close()
			if err != nil {
				log.Fatal(err)
			}
		}()
		data := parseDta(r)
		res,err := AddFile(watcher,data,ps)
		if err != nil{
			w.Write([]byte(err.Error()))
		}
		w.Write([]byte(res))
	}

	return handler
}

func HttpDelFile(watcher *FileWatcher)(httprouter.Handle){

	handler := func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
		defer func() {
			err := r.Body.Close()
			if err != nil {
				log.Fatal(err)
			}
		}()
		data := parseDta(r)
		res,err := DelFile(watcher,data,ps)
		if err != nil{
			w.Write([]byte(err.Error()))
		}
		w.Write([]byte(res))
	}

	return handler
}


func HttpServer(watcher *FileWatcher){
	router := httprouter.New()

	router.PUT("/add",HttpAddFile(watcher))
	router.DELETE("/file/:name",HttpDelFile(watcher))

	err := http.ListenAndServe(":8080", router)
	if err != nil{
		log.Fatal(err)
	}
}